<?php
/**
 * News action controller
 * 
 * @author paq
 *
 */
class Controller_News extends Controller_Action
{
	public function __construct(Controller_Front $frontController)
	{
		parent::__construct('news', $frontController);
	}
		
	public function indexAction()
	{
		$criteria = new Criteria();
		$news;
		
		if (isset($_GET['id_news'])) {
			$criteria->add(NewsPeer::ID_NEWS, $_GET['id_news'], Criteria::EQUAL);
			
			$news = NewsPeer::doSelectOne($criteria);
			
			if (empty($news)) {
				return $this->fail('Selected news does not exist.');
			}
			
			Manager_News::onClick($news);
			$news = array($news);
		} else {
			$criteria->addDescendingOrderByColumn(NewsPeer::DATE);
			/*$criteria->add(
				NewsPeer::ID_REQUEST_STATUS, 
				Manager_RequestStatus::getDone()->getIdRequestStatus(), 
				Criteria::EQUAL
			);*/
			$news = NewsPeer::doSelect($criteria);
		}
		
		$newsRatings = array();
		
		foreach ($news as $one) {
			$newsRatings[$one->getIdNews()] = Manager_News::getRating($one);
		}
		
		//var_dump($newsRatings);
		
		$this->assign('news', $news);
		$this->assign('newsratings', $newsRatings);
		
		$this->display('news.tpl');
	}
	
	public function rateAction()
	{
		if (isset($_GET['id_news'], $_GET['good'])) {
			$news = NewsPeer::retrieveByPK($_GET['id_news']);
			$user = Manager_User::getUser();
			
			if (empty($user)) {
				return $this->fail('Only registered user can rate news.');
			}
			
			if (empty($news)) {
				return $this->indexAction();
			}
			
			$rate = ($_GET['good'] == 'yes') ? true : false;
			
			Manager_News::rate($news, $user, $rate);
			
			$this->ok('You have rated the news.');
		}
		
		return $this->indexAction();
	}
	
	public function readAction()
	{
		if (isset($_GET['id_news'])) {
			$news = NewsPeer::retrieveByPK($_GET['id_news']);
			
			if (empty($news)) {
				return $this->indexAction();
			}
			
			Manager_News::onRead($news);
			
			return $this->indexAction();
		}
	}
}